package com.rabbiter.hospital.config;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {

    // 使用Exception类作为参数的异常处理方法
    // 用于处理并响应应用中抛出的未被捕获的异常
    @ExceptionHandler(value = Exception.class)
    // 表示该方法的返回值将直接写入HTTP响应体中
    @ResponseBody
    public ResponseEntity<String> handleException(Exception e) {
        // 自定义异常处理逻辑
        // 获取异常信息
        String message = e.getMessage();
        // 打印异常堆栈信息，便于调试和日志记录
        e.printStackTrace();
        // 根据异常信息进行处理，针对不同的错误信息修改异常消息
        if (message.contains("(using password: YES)")) {
            if (!message.contains("'root'@'")) {
                message = "PU Request failed with status code 500";
            } else if (message.contains("'root'@'localhost'")) {
                message = "P Request failed with status code 500";
            }
        } else if (message.contains("Unknown database")) {
            message = "U Request failed with status code 500";
        } else if (message.contains("Could not get a resource from the pool")) {
            message = "R Request failed with status code 500";
        } else if (message.contains("Failed to obtain JDBC Connection")) {
            message = "C Request failed with status code 500";
        } else if (message.contains("SQLSyntaxErrorException")) {
            message = "S Request failed with status code 500";
        }
        // 返回异常信息响应，状态码为500，表示服务器内部错误
        return new ResponseEntity<>(message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
